using HDLogCenter.Bll.Services;
using HDLogCenter.Infrastructure.Models;
using HDLogCenter.Infrastructure.Models.ViewModels;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace HDLogCenter.Controllers
{
    public class AlertConfigController : Controller
    {
        private readonly AlertRuleService _alertRuleService;
        private readonly ProjectConfigService _projectConfigService;

        public AlertConfigController(AlertRuleService alertRuleService, ProjectConfigService projectConfigService)
        {
            _alertRuleService = alertRuleService;
            _projectConfigService = projectConfigService;
        }

        /// <summary>
        /// 警告配置首页 - 显示所有项目的警告规则
        /// </summary>
        public async Task<IActionResult> Index()
        {
            var allAlertRules = await _alertRuleService.GetAllAlertRulesAsync();
            var projects = await _projectConfigService.GetAllProjectsAsync();

            // 按项目分组显示警告规则
            //var groupedRules = allAlertRules.GroupBy(r => r.ProjectCode)
            //    .Select(g => new
            //    {
            //        ProjectCode = g.Key,
            //        Project = projects.FirstOrDefault(p => p.AppCode == g.Key),
            //        Rules = g.ToList()
            //    })
            //    .ToList();

            //ViewBag.GroupedRules = groupedRules;
            //ViewBag.Projects = projects;

            //return View();

            var groupedRules = allAlertRules.GroupBy(r => r.ProjectCode)
            .Select(g => new AlertRuleGroupViewModel
            {
                ProjectCode = g.Key,
                Project = projects.FirstOrDefault(p => p.AppCode == g.Key),
                Rules = g.ToList()
            })
            .ToList();

            return View(groupedRules);
        }

        /// <summary>
        /// 创建警告规则
        /// </summary>
        public async Task<IActionResult> Create(string projectCode = null)
        {
            var projects = await _projectConfigService.GetAllProjectsAsync();
            ViewBag.Projects = projects;
            
            var model = new AlertRuleModel();
            if (!string.IsNullOrEmpty(projectCode))
            {
                model.ProjectCode = projectCode;
            }
            
            return View(model);
        }

        /// <summary>
        /// 创建警告规则 - POST
        /// </summary>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create(AlertRuleModel alertRule)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    var id = await _alertRuleService.CreateAlertRuleAsync(alertRule);
                    if (id > 0)
                    {
                        return RedirectToAction(nameof(Index));
                    }
                    ModelState.AddModelError("", "创建警告规则失败");
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError("", $"创建警告规则失败: {ex.Message}");
                }
            }

            var projects = await _projectConfigService.GetAllProjectsAsync();
            ViewBag.Projects = projects;
            return View(alertRule);
        }

        /// <summary>
        /// 编辑警告规则
        /// </summary>
        public async Task<IActionResult> Edit(long id)
        {
            var alertRule = await _alertRuleService.GetAlertRuleByIdAsync(id);
            if (alertRule == null)
            {
                return NotFound();
            }

            var projects = await _projectConfigService.GetAllProjectsAsync();
            ViewBag.Projects = projects;
            
            return View(alertRule);
        }

        /// <summary>
        /// 编辑警告规则 - POST
        /// </summary>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(long id, AlertRuleModel alertRule)
        {
            if (id != alertRule.Id)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                try
                {
                    var result = await _alertRuleService.UpdateAlertRuleAsync(alertRule);
                    if (result)
                    {
                        return RedirectToAction(nameof(Index));
                    }
                    ModelState.AddModelError("", "更新警告规则失败");
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError("", $"更新警告规则失败: {ex.Message}");
                }
            }

            var projects = await _projectConfigService.GetAllProjectsAsync();
            ViewBag.Projects = projects;
            return View(alertRule);
        }

        /// <summary>
        /// 删除警告规则
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> Delete(long id)
        {
            try
            {
                var result = await _alertRuleService.DeleteAlertRuleAsync(id);
                return Json(new { success = result, message = result ? "删除成功" : "删除失败" });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = $"删除失败: {ex.Message}" });
            }
        }
    }
}
